package cn.zyx.common.utils.sys;

import cn.zyx.common.properites.CacheProperties;
import cn.zyx.common.utils.cache.redis.RedisUtils;
import cn.zyx.sys.entity.DictType;
import cn.zyx.sys.entity.DictValue;
import cn.zyx.sys.service.DictTypeService;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.commons.lang3.StringUtils;

import java.util.List;
import java.util.Map;

/**
 * 字典工具类
 */
public class DictUtils {

	public static String getDictLabel(String value, String type, String defaultLabel){
		if (StringUtils.isNotBlank(type) && StringUtils.isNotBlank(value)){
			for (DictValue dictValue : getDictList(type)){
				if (value.equals(dictValue.getValue())){
					return dictValue.getLabel();
				}
			}
		}
		return defaultLabel;
	}

	public static String getDictLabels(String values, String type, String defaultValue){
		if (StringUtils.isNotBlank(type) && StringUtils.isNotBlank(values)){
			List<String> valueList = Lists.newArrayList();
			for (String value : StringUtils.split(values, ",")){
				valueList.add(getDictLabel(value, type, defaultValue));
			}
			return StringUtils.join(valueList, ",");
		}
		return defaultValue;
	}

	public static String getDictValue(String label, String type, String defaultLabel){
		if (StringUtils.isNotBlank(type) && StringUtils.isNotBlank(label)){
			for (DictValue dictValue : getDictList(type)){
				if (label.equals(dictValue.getLabel())){
					return dictValue.getValue();
				}
			}
		}
		return defaultLabel;
	}

	public static List<DictValue> getDictList(String type){
		Map<String, List<DictValue>> dictMap =  RedisUtils.getCacheObject(CacheProperties.CACHE_DICT_MAP);
		if (dictMap==null){
			dictMap = Maps.newHashMap();
			for (DictType dictType : SpringContextHolderUtils.getBean(DictTypeService.class).findList(new DictType())){
				List<DictValue> dictList = dictMap.get(dictType.getType());
				dictType = SpringContextHolderUtils.getBean(DictTypeService.class).get(dictType.getId());
				if (dictList != null){
					dictList.addAll(dictType.getDictValueList());
				}else{
					dictMap.put(dictType.getType(), Lists.newArrayList(dictType.getDictValueList()));
				}
			}
			RedisUtils.setCacheObject(CacheProperties.CACHE_DICT_MAP, dictMap);
		}
		List<DictValue> dictList = dictMap.get(type);
		if (dictList == null){
			dictList = Lists.newArrayList();
		}
		return dictList;
	}

	public static Map<String, List<DictValue>> getDictMap() {
		// 从缓存获取字典列表值
		Map<String, List<DictValue>> dictMap = RedisUtils.getCacheObject(CacheProperties.CACHE_DICT_MAP);
		if (dictMap == null) {
			dictMap = Maps.newHashMap();
			List<DictType> dict = SpringContextHolderUtils.getBean(DictTypeService.class).getDict();
			for (DictType dictType : dict) {
				dictMap.put(dictType.getType(), dictType.getDictValueList());
			}
			RedisUtils.setCacheObject(CacheProperties.CACHE_DICT_MAP, dictMap);
		}

		return dictMap;
	}
}
